package com.bestom.usbdevelop;

public class HexUtil {

    public static String makeChecksum(String data) {
        if (data == null || data.equals("")) {
            return "";
        }
        int total = 0;
        int len = data.length();
        int num = 0;
        while (num < len) {
            String s = data.substring(num, num + 2);
            System.out.println(s);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        //用256求余最大是255，即16进制的FF
        int mod = total % 256;
        String hex = Integer.toHexString(mod);
        len = hex.length();
        // 如果不够校验位的长度，补0,这里用的是两位校验
        if (len < 2) hex = "0" + hex;
        return hex;
    }

    public static String intToHex(int data){
        String hex= Integer.toHexString(data);
        if (hex.length() == 1) hex="000"+hex;
        else if (hex.length() == 2) hex="00"+hex;
        else if (hex.length() == 3) hex="0"+hex;
        return hex;
    }

    public static String intToHex(String data){
        return intToHex(Integer.parseInt(data));
    }
}
